using Hydrogen.Cmd.Interfaces;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Hydrogen.Cmd.Commands
{
    /// <summary>
    /// 编码格式转换
    /// </summary>
    [CommandFlag("ec", "encoding")]
    class EncodingConvertCommand : CommandBase
    {
        public static new string Discription
        {
            get
            {
                string description = @"编码格式转换
                    【转换目录下某类文件】-f gb2312 -t utf-8 -d xx\output -pattern *.loc
                    【转换某个文件】-f gb2312 -t utf-8 -p xx\output\aa.bb";
                return description;
            }
        }
        public override void Invoke(params string[] args)
        {
            Dictionary<string, string> argsDic = GetArgsDic(args, out List<string> oldArgsGroup);

            string fromEncoding = GetArgs(argsDic, "-f", "utf-8");
            string toEncoding = GetArgs(argsDic, "-t", "utf-8");
            string source = GetArgs(argsDic, "-p", "");
            string dirPath = GetArgs(argsDic, "-d", "");

            if (!string.IsNullOrEmpty(dirPath) && !string.IsNullOrEmpty(GetArgs(argsDic, "-pattern", "")))
            {
                if (!Directory.Exists(dirPath))
                {
                    Console.ConsoleLog.LogError("未找到目录：" + dirPath);
                    return;
                }
                var pattern = GetArgs(argsDic, "-pattern", "");
                ForEachFile(dirPath, f =>
                {
                    try
                    {
                        Convert(fromEncoding, toEncoding, f);
                        Console.ConsoleLog.Log("处理完成：" + f);
                    }
                    catch (Exception ex)
                    {
                        Console.ConsoleLog.LogError(ex.ToString());
                    }
                }, pattern);

                return;
            }

            if (string.IsNullOrEmpty(source))
            {
                Console.ConsoleLog.LogError("使用参数 \"-p aaa.bbb\" 传入路径");
                return;
            }



            if (!File.Exists(source))
            {
                Console.ConsoleLog.LogError("未找到文件：" + source);
                return;
            }

            Convert(fromEncoding, toEncoding, source);
        }

        private static void Convert(string fromEncoding, string toEncoding, string path)
        {
            var data = File.ReadAllBytes(path);
            var newData = EncodingConvert(Encoding.GetEncoding(toEncoding),
                Encoding.GetEncoding(fromEncoding),
                data);
            File.WriteAllText(path, newData);
        }

        public static string EncodingConvert(Encoding src, Encoding dst, byte[] bytes)
        {
            var newBytes = Encoding.Convert(src, dst, bytes);
            return dst.GetString(bytes);
        }

        /// <summary>
        /// 递归遍历目录及其子目录内的所有文件
        /// </summary>
        /// <param name="dirPath">目录</param>
        /// <param name="action"></param>
        /// <param name="pattern">扩展名，如 .xlsx</param>
        public static void ForEachFile(string dirPath, Action<string> action, params string[] pattern)
        {
            if (!Directory.Exists(dirPath)) return;

            //如果没有给扩展名，则默认我全都要
            if (pattern.Length <= 0) pattern = new string[] { "*" };

            //遍历本目录下的所有文件
            foreach (var item in pattern)
            {
                string[] files = Directory.GetFiles(dirPath, "*" + item);
                if (files == null || files.Length <= 0) continue;//如果这个目录底下没有文件，就跳过
                foreach (var f in files)
                {
                    action?.Invoke(f);
                }
            }

            //遍历本目录下的所有子目录
            foreach (var item in Directory.GetDirectories(dirPath))
            {
                ForEachFile(item, action, pattern);
            }
        }
    }
}
